package com.weetop.aklyscan.activity.qingdan;

import android.Manifest;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Base64;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.pickerview.TimePickerView;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.classic.adapter.BaseAdapterHelper;
import com.classic.adapter.CommonRecyclerAdapter;
import com.honeywell.aidc.AidcManager;
import com.honeywell.aidc.BarcodeFailureEvent;
import com.honeywell.aidc.BarcodeReadEvent;
import com.honeywell.aidc.BarcodeReader;
import com.honeywell.aidc.TriggerStateChangeEvent;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.weetop.aklyscan.R;
import com.weetop.aklyscan.activity.DayinDialog1;
import com.weetop.aklyscan.activity.DayinDialog2;
import com.weetop.aklyscan.activity.DayinDialog3;
import com.weetop.aklyscan.activity.Fragment_send_out;
import com.weetop.aklyscan.activity.ImgDialog;
import com.weetop.aklyscan.activity.MainActivity;
import com.weetop.aklyscan.activity.lanya.BluetoothLeClass;
import com.weetop.aklyscan.activity.lanya.Bluetooth_Scale;
import com.weetop.aklyscan.activity.lanya.DeviceListActivity;
import com.weetop.aklyscan.activity.lanya.PubFunction;
import com.weetop.aklyscan.appConfig.GlideImageLoader;
import com.weetop.aklyscan.appConfig.MyApplication;
import com.weetop.aklyscan.base.BaseActivity;
import com.weetop.aklyscan.base.BaseUrl;
import com.weetop.aklyscan.base.mvp.BaseModel;
import com.weetop.aklyscan.bean.KuaiDiBean;
import com.weetop.aklyscan.bean.KuaiDiImgBean;
import com.weetop.aklyscan.bean.MailBean;
import com.weetop.aklyscan.bean.MailBean1;
import com.weetop.aklyscan.bean.MailNumberBean;
import com.weetop.aklyscan.bean.OfficeBean;
import com.weetop.aklyscan.bean.OnLineOrderBean;
import com.weetop.aklyscan.presenter.DetailedPresent;
import com.weetop.aklyscan.utils.BaseUtils;
import com.weetop.aklyscan.utils.MyTimePicker1;
import com.weetop.aklyscan.utils.widget.MyDialogUtil;
import com.weetop.aklyscan.view.DetailedView;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import ZPL.ZPLPrinterHelper;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cc.shinichi.library.tool.utility.ui.ToastUtil;

public class DetailedActivity extends BaseActivity<DetailedPresent> implements DetailedView, BarcodeReader.BarcodeListener, BarcodeReader.TriggerListener {
    @BindView(R.id.recyclerView1)
    RecyclerView recyclerView1;
    @BindView(R.id.recyclerView2)
    RecyclerView recyclerView2;
    @BindView(R.id.recyclerView3)
    RecyclerView recyclerView3;
    @BindView(R.id.recyclerView4)
    RecyclerView recyclerView4;
    @BindView(R.id.orderid)
    TextView orderid;
    @BindView(R.id.type)
    TextView type;
    @BindView(R.id.totle_num)
    TextView totle_num;
    @BindView(R.id.start_time)
    TextView start_time;
    @BindView(R.id.stop_time)
    TextView stop_time;
    @BindView(R.id.start_time_ll)
    LinearLayout start_time_ll;
    @BindView(R.id.stop_time_ll)
    LinearLayout stop_time_ll;
    @BindView(R.id.yidayin_ll)
    LinearLayout yidayin_ll;
    @BindView(R.id.weidayin_ll)
    LinearLayout weidayin_ll;
    @BindView(R.id.dayin_img)
    ImageView dayin_img;
    @BindView(R.id.dayin_type)
    TextView dayin_type;
    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.chanpin_dx)
    TextView chanpin_dx;
    @BindView(R.id.sjzl)
    TextView sjzl;
    @BindView(R.id.lianjie)
    TextView lianjie;
    @BindView(R.id.order_type)
    TextView order_type;
    @BindView(R.id.pic_type_ll)
    LinearLayout pic_type_ll;
    @BindView(R.id.pic_type)
    TextView pic_type;
    @BindView(R.id.mailName)
    TextView mailName;
    @BindView(R.id.mailCode)
    TextView mailCode;
    @BindView(R.id.mail_code_ll1)
    LinearLayout mail_code_ll1;
    @BindView(R.id.mail_code_ll2)
    LinearLayout mail_code_ll2;
    @BindView(R.id.shengcheng)
    TextView shengcheng;
    @BindView(R.id.mail_code1)
    TextView mail_code1;
    @BindView(R.id.mail_code2)
    TextView mail_code2;
    @BindView(R.id.btn_save)
    TextView btn_save;
    @BindView(R.id.tuxiang)
    TextView tuxiang;
    @BindView(R.id.iv_bluetooth_status)
    ImageView iv_bluetooth_status;
    @BindView(R.id.iv_img)
    ImageView iv_img;
    private CommonRecyclerAdapter<OnLineOrderBean.ListDataBean> adapter1;
    private List<OnLineOrderBean.ListDataBean> list1 = new ArrayList<>();
    private CommonRecyclerAdapter<OnLineOrderBean.ListDataBean> adapter2;
    private List<OnLineOrderBean.ListDataBean> list2 = new ArrayList<>();

    private CommonRecyclerAdapter<OfficeBean.DataBean> adapter3;
    private List<OfficeBean.DataBean> list3 = new ArrayList<>();
    private CommonRecyclerAdapter<OfficeBean.DataBean> adapter4;
    private List<OfficeBean.DataBean> list4 = new ArrayList<>();

    private List<MailBean.DataBean> mailList = new ArrayList<>();
    private List<MailBean1.DataBean> mailList1 = new ArrayList<>();
    private String mCode, orderID;
    public static String templateCode, mailCode1, mailID1, mailQuantity;
    private boolean dyjStatus;
    private int i3 = 0;
    private String pic3 = "";

    private OnLineOrderBean onLineOrderBean;
    private OfficeBean officeBean;
    private OfficeBean.DataBean officedataBean;
    private KuaiDiBean kuaiDiBean;
    OnLineOrderBean.ListDataBean listDataBean;

    Handler handler1 = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                getDayinStatus();
                handler1.sendEmptyMessageDelayed(1, 3000);
            } else if (msg.what == 2) {
                if (MyApplication.b_scaleIsConnect) {
                    iv_bluetooth_status.setImageResource(R.mipmap.bluetooth_true);
                    if (MyApplication.isBluePlay == 0 || MyApplication.isBluePlay == 2) {
                        MyApplication.isBluePlay = 1;
                        playRing("lianjiesuccess.mp3");
                    }
                } else {
                    MyApplication.b_scaleIsConnect = false;
                    iv_bluetooth_status.setImageResource(R.mipmap.bluetooth_error);
                    if (MyApplication.isBluePlay == 1) {
                        MyApplication.isBluePlay = 2;
                        playRing("lianjieerror.mp3");
                    }
                }
            } else if (msg.what == 3) {
                if (msg.obj != null) {
                    String orderSn = (String) msg.obj;
                    mPresenter.updateOrder(orderSn);
                } else {
                    mPresenter.updateOrder(listDataBean.getOrder_sn());
                }
            } else if (msg.what == 4) {
                shengcheng.setEnabled(true);
                chanpin_dx.setText("");
                sjzl.setText("");
                mail_code1.setText("");
                mail_code2.setText("");
                pic3 = "";
                if ((int) dayin_type.getTag() == 1) {
                    mPresenter.updateOrder2(officeBean.getList_data().get(i3).getOrder_sn());
                } else {
                    mPresenter.updateOrder3(officeBean.getList_data().get(i3).getOrder_sn());
                }
            } else if (msg.what == 5) {
                if (TextUtils.isEmpty(pic3))
                    if (kuaiDiBean != null)
                        mPresenter.getKuaiDiImg(((int) dayin_type.getTag() + 1) + "", officedataBean.getOrder_sn(), kuaiDiBean.getKuaidinum());
            } else if (msg.what == 6) {
                DayinDialog3 dayinDialog = new DayinDialog3(DetailedActivity.this, list_i);
                dayinDialog.show();
                playRing("dayinwancheng.mp3");
            } else if (msg.what == 7) {
//                hideLoading();
//                playRing("dayinwancheng.mp3");
                if (j == onLineOrderBean.getList().size() - 1) {
                    dissmissDialog();
                    DayinDialog3 dayinDialog = new DayinDialog3(DetailedActivity.this, list_i);
                    dayinDialog.show();
                    dayinDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            getList();
                        }
                    });
//                Looper.loop();
//                    playRing("dayinwancheng.mp3");
                } else {
                    j++;
                    new Thread(thread).start();
                }
            }
        }
    };

    @Override
    protected DetailedPresent createPresenter() {
        return new DetailedPresent(this, this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detailed);
        ButterKnife.bind(this);
        recyclerView1.setLayoutManager(new LinearLayoutManager(mActivity));
        if (MyApplication.b_scaleIsConnect == Boolean.TRUE) {
            iv_bluetooth_status.setImageResource(R.mipmap.bluetooth_true);
        } else {
            iv_bluetooth_status.setImageResource(R.mipmap.bluetooth_error);
        }
//        DayinDialog1 dayinDialog1 = new DayinDialog1(DetailedActivity.this, "");
//        dayinDialog1.show();
//        dayinDialog1.setOnDismissListener(new DialogInterface.OnDismissListener() {
//            @Override
//            public void onDismiss(DialogInterface dialog) {
//                ToastUtils.showShort("点了返回");
//            }
//        });
        adapter1 = new CommonRecyclerAdapter<OnLineOrderBean.ListDataBean>(mActivity, R.layout.item_details1, list1) {

            @Override
            public void onUpdate(BaseAdapterHelper helper, OnLineOrderBean.ListDataBean item, int position) {
//                if (i3 == position) {
//                    helper.setBackgroundRes(R.id.totle_ll, R.color.bt2);
//                } else {
//                    helper.setBackgroundRes(R.id.totle_ll, R.drawable.tab_line);
//                }
                helper.setText(R.id.tv_xuhao, position + 1 + "");
                helper.setText(R.id.order_code, item.getOrder_sn());
                helper.setOnClickListener(R.id.img, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        System.out.println(list1.size() + ":" + position);
                        if ((int) type.getTag() == 0) {
                            if (TextUtils.isEmpty(item.getQd_image())) {
                                ToastUtil.getInstance()._short(DetailedActivity.this, "未获取到图片，请先去生成");
                                return;
                            }
                            ImgDialog1 imgDialog = new ImgDialog1(DetailedActivity.this, item.getQd_image());
                            imgDialog.show();
                        } else {
                            if ((int) pic_type.getTag() == 0) {
                                if (TextUtils.isEmpty(item.getQd_image())) {
                                    ToastUtil.getInstance()._short(DetailedActivity.this, "未获取到图片，请先去生成");
                                    return;
                                }
                                ImgDialog1 imgDialog = new ImgDialog1(DetailedActivity.this, item.getQd_image());
                                imgDialog.show();
                            } else {
                                if (TextUtils.isEmpty(item.getQd_images_two())) {
                                    ToastUtil.getInstance()._short(DetailedActivity.this, "未获取到图片，请先去生成");
                                    return;
                                }
//                            BaseUrl.url+"/uploads/pps/20210810/20210810112145515.png";
                                ImgDialog1 imgDialog = new ImgDialog1(DetailedActivity.this, item.getQd_images_two());
                                imgDialog.show();
                            }
                        }
                    }
                });

                helper.setOnClickListener(R.id.totle_ll, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        listDataBean = item;
//                        i3 = position;
//                        notifyDataSetChanged();
                        if (!ZPLPrinterHelper.IsOpened()) {
                            ToastUtil.getInstance()._short(mContext, "打印机连接失败");
                            return;
                        }
                        if (!dyjStatus) {
                            return;
                        }
                        if ((int) type.getTag() == 0) {
                            if (TextUtils.isEmpty(item.getQd_image())) {
                                ToastUtil.getInstance()._short(mContext, "未获取到图片，请先去生成");
                                return;
                            }
                        } else {
                            if ((int) pic_type.getTag() == 0) {
                                if (TextUtils.isEmpty(item.getQd_image())) {
                                    ToastUtil.getInstance()._short(mContext, "未获取到图片，请先去生成");
                                    return;
                                }
                            } else {
                                if (TextUtils.isEmpty(item.getQd_images_two())) {
                                    ToastUtil.getInstance()._short(mContext, "未获取到图片，请先去生成");
                                    return;
                                }
                            }
                        }
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Bitmap bitmap = null;
                                    if ((int) type.getTag() == 0) {
                                        bitmap = GlideImageLoader.getBitmap(BaseUrl.url2 + item.getQd_image());
                                    } else {
                                        if ((int) pic_type.getTag() == 0) {
                                            bitmap = GlideImageLoader.getBitmap(BaseUrl.url2 + item.getQd_image());
                                        } else {
                                            bitmap = GlideImageLoader.getBitmap(BaseUrl.url2 + item.getQd_images_two());
                                        }
                                    }
                                    if (TextUtils.isEmpty(MainActivity.userInfoBean.getPrint_paper_width())) {
                                        ToastUtil.getInstance()._short(mContext, "纸张宽度不能为空");
                                        return;
                                    }
                                    if (TextUtils.isEmpty(MainActivity.userInfoBean.getPrint_deviation_x())) {
                                        ToastUtil.getInstance()._short(mContext, "水平偏移不能为空");
                                        return;
                                    }
                                    if (TextUtils.isEmpty(MainActivity.userInfoBean.getPrint_deviation_y())) {
                                        ToastUtil.getInstance()._short(mContext, "垂直偏移不能为空");
                                        return;
                                    }
                                    MainActivity.mZPL.start();
//                                    if ((int) type.getTag() == 0) {
//                                        MainActivity.mZPL.WriteData(("^LL " + item.getQd_image_height()).getBytes());
//                                    } else {
//                                        if ((int) pic_type.getTag() == 0) {
//                                            MainActivity.mZPL.WriteData(("^LL " + item.getQd_image_height()).getBytes());
//                                        } else {
//                                            MainActivity.mZPL.WriteData(("^LL " + item.getQd_image_two_height()).getBytes());
//                                        }
//                                    }
                                    MainActivity.mZPL.printData("^LL" + bitmap.getHeight() + "\r\n");
                                    MainActivity.mZPL.PW(MainActivity.userInfoBean.getPrint_paper_width());
                                    MainActivity.mZPL.printBitmap(MainActivity.userInfoBean.getPrint_deviation_x(),
                                            MainActivity.userInfoBean.getPrint_deviation_y(), bitmap);
                                    MainActivity.mZPL.PQ("1", "1", "1", "Y");
                                    int i = MainActivity.mZPL.end();
                                    Looper.prepare();
                                    if (i == 0) {
                                        DayinDialog1 dayinDialog1 = new DayinDialog1(DetailedActivity.this, i + "");
                                        dayinDialog1.show();
                                        playRing("dayinwancheng.mp3");
                                        Message message = new Message();
                                        message.what = 3;
                                        message.obj = item.getOrder_sn();
                                        handler1.sendMessage(message);
                                    } else {
                                        DayinDialog2 dayinDialog2 = new DayinDialog2(DetailedActivity.this, i + "");
                                        dayinDialog2.show();
                                        playRing("dayinshibai.mp3");
                                    }
                                    Looper.loop();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }).

                                start();
                    }
                });
            }
        };
        recyclerView1.setAdapter(adapter1);
        recyclerView1.setNestedScrollingEnabled(false);
        recyclerView2.setLayoutManager(new LinearLayoutManager(mActivity));
        adapter2 = new CommonRecyclerAdapter<OnLineOrderBean.ListDataBean>(mActivity, R.layout.item_details2, list2) {
            @Override
            public void onUpdate(BaseAdapterHelper helper, OnLineOrderBean.ListDataBean item,
                                 int position) {
                if (i3 == position) {
                    helper.setBackgroundRes(R.id.totle_ll, R.color.bt2);
                } else {
                    helper.setBackgroundRes(R.id.totle_ll, R.drawable.tab_line);
                }
                helper.setText(R.id.tv_xuhao, position + 1 + "");
                helper.setText(R.id.order_code, item.getOrder_sn());
                helper.setText(R.id.new_time, item.getPrint_time());
                helper.setText(R.id.num, item.getPrint_count() + "");
                helper.setOnClickListener(R.id.img, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        System.out.println(list2.size() + ":" + position);
                        if ((int) type.getTag() == 0) {
                            if (TextUtils.isEmpty(item.getQd_image())) {
                                ToastUtil.getInstance()._short(DetailedActivity.this, "未获取到图片，请先去生成");
                                return;
                            }
                            ImgDialog1 imgDialog = new ImgDialog1(DetailedActivity.this, item.getQd_image());
                            imgDialog.show();
                        } else {
                            if ((int) pic_type.getTag() == 0) {
                                if (TextUtils.isEmpty(item.getQd_image())) {
                                    ToastUtil.getInstance()._short(DetailedActivity.this, "未获取到图片，请先去生成");
                                    return;
                                }
                                ImgDialog1 imgDialog = new ImgDialog1(DetailedActivity.this, item.getQd_image());
                                imgDialog.show();
                            } else {
                                if (TextUtils.isEmpty(item.getQd_images_two())) {
                                    ToastUtil.getInstance()._short(DetailedActivity.this, "未获取到图片，请先去生成");
                                    return;
                                }
                                ImgDialog1 imgDialog = new ImgDialog1(DetailedActivity.this, item.getQd_images_two());
                                imgDialog.show();
                            }
                        }
                    }
                });
                helper.setOnClickListener(R.id.totle_ll, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        listDataBean = item;
                        i3 = position;
                        if ((int) type.getTag() == 0) {
                            pic3 = item.getQd_image();
                        } else {
                            if ((int) pic_type.getTag() == 0) {
                                pic3 = item.getQd_image();
                            } else {
                                pic3 = item.getQd_images_two();
                            }
                        }
                        notifyDataSetChanged();
//                        if (!ZPLPrinterHelper.IsOpened()) {
//                            ToastUtil.getInstance()._short(mContext, "打印机连接失败");
//                            return;
//                        }
//                        if (!dyjStatus) {
//                            return;
//                        }
//                        if ((int) type.getTag() == 0) {
//                            if (TextUtils.isEmpty(item.getQd_image())) {
//                                ToastUtil.getInstance()._short(mContext, "未获取到图片，请先去生成");
//                                return;
//                            }
//                        } else {
//                            if ((int) pic_type.getTag() == 0) {
//                                if (TextUtils.isEmpty(item.getQd_image())) {
//                                    ToastUtil.getInstance()._short(mContext, "未获取到图片，请先去生成");
//                                    return;
//                                }
//                            } else {
//                                if (TextUtils.isEmpty(item.getQd_images_two())) {
//                                    ToastUtil.getInstance()._short(mContext, "未获取到图片，请先去生成");
//                                    return;
//                                }
//                            }
//                        }
//                        new Thread(new Runnable() {
//                            @Override
//                            public void run() {
//                                try {
//                                    Bitmap bitmap = null;
//                                    if ((int) type.getTag() == 0) {
//                                        bitmap = GlideImageLoader.getBitmap(BaseUrl.url2 + item.getQd_image());
//                                    } else {
//                                        if ((int) pic_type.getTag() == 0) {
//                                            bitmap = GlideImageLoader.getBitmap(BaseUrl.url2 + item.getQd_image());
//                                        } else {
//                                            bitmap = GlideImageLoader.getBitmap(BaseUrl.url2 + item.getQd_images_two());
//                                        }
//                                    }
//                                    if (TextUtils.isEmpty(MainActivity.userInfoBean.getPrint_paper_width())) {
//                                        ToastUtil.getInstance()._short(mContext, "纸张宽度不能为空");
//                                        return;
//                                    }
//                                    if (TextUtils.isEmpty(MainActivity.userInfoBean.getPrint_deviation_x())) {
//                                        ToastUtil.getInstance()._short(mContext, "水平偏移不能为空");
//                                        return;
//                                    }
//                                    if (TextUtils.isEmpty(MainActivity.userInfoBean.getPrint_deviation_y())) {
//                                        ToastUtil.getInstance()._short(mContext, "垂直偏移不能为空");
//                                        return;
//                                    }
//                                    MainActivity.mZPL.start();
//                                    if ((int) type.getTag() == 0) {
//                                        MainActivity.mZPL.WriteData(("^LL " + item.getQd_image_height()).getBytes());
//                                    } else {
//                                        if ((int) pic_type.getTag() == 0) {
//                                            MainActivity.mZPL.WriteData(("^LL " + item.getQd_image_height()).getBytes());
//                                        } else {
//                                            MainActivity.mZPL.WriteData(("^LL " + item.getQd_image_two_height()).getBytes());
//                                        }
//                                    }
//                                    MainActivity.mZPL.PW(MainActivity.userInfoBean.getPrint_paper_width());
//                                    MainActivity.mZPL.printBitmap(MainActivity.userInfoBean.getPrint_deviation_x(),
//                                            MainActivity.userInfoBean.getPrint_deviation_y(), bitmap);
//                                    MainActivity.mZPL.PQ("1", "1", "1", "Y");
//                                    int i = MainActivity.mZPL.end();
//                                    Looper.prepare();
//                                    if (i == 0) {
//                                        DayinDialog1 dayinDialog1 = new DayinDialog1(DetailedActivity.this, i + "");
//                                        dayinDialog1.show();
//                                        playRing("dayinwancheng.mp3");
//                                        mPresenter.updateOrder(item.getOrder_sn());
//                                    } else {
//                                        DayinDialog2 dayinDialog2 = new DayinDialog2(DetailedActivity.this, i + "");
//                                        dayinDialog2.show();
//                                        playRing("shibai.mp3");
//                                    }
//                                    Looper.loop();
//                                } catch (Exception e) {
//                                    e.printStackTrace();
//                                }
//                            }
//                        }).start();
                    }
                });
            }
        };
        recyclerView2.setAdapter(adapter2);
        recyclerView2.setNestedScrollingEnabled(false);
        recyclerView3.setLayoutManager(new LinearLayoutManager(mActivity));
        adapter3 = new CommonRecyclerAdapter<OfficeBean.DataBean>(mActivity, R.layout.item_details1, list3) {

            @Override
            public void onUpdate(BaseAdapterHelper helper, OfficeBean.DataBean item,
                                 int position) {
                helper.setText(R.id.tv_xuhao, position + 1 + "");
                helper.setText(R.id.order_code, item.getOrder_sn());
                if (i3 == position) {
                    helper.setBackgroundRes(R.id.totle_ll, R.color.bt2);
                } else {
                    helper.setBackgroundRes(R.id.totle_ll, R.drawable.tab_line);
                }
                helper.setOnClickListener(R.id.img, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        System.out.println(list3.size() + ":" + position);
                        if ((int) dayin_type.getTag() == 2) {
                            InfoDialog1 infoDialog1 = new InfoDialog1(DetailedActivity.this,
                                    item.getShop_sh_name() + " " + item.getShop_sh_phone() + "\n" + item.getShop_sh_address(), item.getRemarks(), 0);
                            infoDialog1.show();
                        } else {
                            String address = item.getProvince() + item.getCity() +
                                    item.getArea() + item.getAddress();
                            InfoDialog1 infoDialog1 = new InfoDialog1(DetailedActivity.this,
                                    item.getName() + " " + item.getPhone() + "\n" + address, item.getRemarks(), 1);
                            infoDialog1.show();
                        }
                    }
                });
                helper.setOnClickListener(R.id.totle_ll, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        i3 = position;
                        officedataBean = item;
                        pic3 = item.getImg_base64();
                        chanpin_dx.setText("");
                        sjzl.setText("");
                        mail_code1.setText("");
                        mail_code2.setText("");
                        notifyDataSetChanged();
                    }
                });
            }
        };
        recyclerView3.setAdapter(adapter3);
        recyclerView3.setNestedScrollingEnabled(false);
        recyclerView4.setLayoutManager(new LinearLayoutManager(mActivity));
        adapter4 = new CommonRecyclerAdapter<OfficeBean.DataBean>(mActivity, R.layout.item_details2, list4) {
            @Override
            public void onUpdate(BaseAdapterHelper helper, OfficeBean.DataBean item,
                                 int position) {
                if (i3 == position) {
                    helper.setBackgroundRes(R.id.totle_ll, R.color.bt2);
                } else {
                    helper.setBackgroundRes(R.id.totle_ll, R.drawable.tab_line);
                }
                helper.setText(R.id.tv_xuhao, position + 1 + "");
                helper.setText(R.id.order_code, item.getOrder_sn());
                helper.setText(R.id.new_time, item.getPrint_time());
                helper.setText(R.id.num, item.getPrint_num() + "");
                helper.setOnClickListener(R.id.img, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        System.out.println(list4.size() + ":" + position);
                        if (item.getImg_base64() == null) {
                            ToastUtil.getInstance()._short(DetailedActivity.this, "未获取到图片，请先去生成");
                            return;
                        }
                        ImgDialog imgDialog = new ImgDialog(DetailedActivity.this, item.getImg_base64());
                        imgDialog.show();
                    }
                });
                helper.setOnClickListener(R.id.totle_ll, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        i3 = position;
                        officedataBean = item;
                        pic3 = item.getImg_base64();
                        chanpin_dx.setText("");
                        sjzl.setText("");
                        mail_code1.setText("");
                        mail_code2.setText("");
                        notifyDataSetChanged();
                    }
                });
            }
        };
        recyclerView4.setAdapter(adapter4);
        recyclerView4.setNestedScrollingEnabled(false);
        type.setTag(0);
        dayin_type.setTag(0);
        order_type.setTag(0);
        pic_type.setTag(0);
        mPresenter.mailType();
        mPresenter.mailType1();
        start_time.setText(getTime());
        mPresenter.onlineOrder("", type.getTag().toString(), "", "");
        getList();
//        getDayinStatus();

        initScan();

        getBle();
        mPresenter.Into77();
    }

    String endTime;

    @Override
    public void getInto77Success(BaseModel<String> o) {
        endTime = o.getData();
    }

    @Override
    public void showError(String msg) {
        super.showError(msg);
        ToastUtils.showShort(msg);
    }

    @Override
    public void getMailTypeSuccess(BaseModel<MailBean> o) {
        mailList = o.getData().getList_data();
        if ((int) order_type.getTag() == 1) {
            for (int i = 0; i < mailList.size(); i++) {
                if (MyApplication.getMailCode().equals(mailList.get(i).getId())) {
                    mailName.setText(mailList.get(i).getName());
                    mailCode.setText(mailList.get(i).getCode());
                    mailCode1 = mailList.get(i).getCode();
                    mailID1 = mailList.get(i).getId();
                    return;
                }
//                if (i == mailList1.size() - 1) {
//                    mailName.setText(mailList.get(0).getName());
//                    mailCode.setText(mailList.get(0).getCode());
//                    mailCode1 = mailList.get(0).getCode();
//                    mailID1 = mailList.get(0).getId();
//                }
            }
        }
    }

    @Override
    public void getupdateOrder1Success(BaseModel<String> o) {
        handler1.sendEmptyMessageDelayed(7, 2000);
    }

    @Override
    public void getMailType1Success(BaseModel<MailBean1> o) {
        mailList1 = o.getData().getList();
        if ((int) order_type.getTag() == 0) {
            for (int i = 0; i < mailList1.size(); i++) {
                if (MyApplication.getMailID().equals(mailList1.get(i).getId())) {
                    mailName.setText(mailList1.get(i).getSon_name());
                    mailCode1 = mailList1.get(i).getCode();
                    mailID1 = mailList1.get(i).getId();
                    templateCode = mailList1.get(i).getTemplate_code();
                    mPresenter.surplus(mailList1.get(i).getId());
                    return;
                }
//                if (i == mailList1.size() - 1) {
//                    mailName.setText(mailList1.get(0).getSon_name());
//                    mailCode1 = mailList1.get(0).getCode();
//                    mailID1 = mailList1.get(0).getId();
//                    templateCode = mailList1.get(0).getTemplate_code();
//                    mPresenter.surplus(mailList1.get(0).getId());
//                }
            }
        }
    }

    @Override
    public void getsurplusError(String error) {
        ToastUtils.showShort("未查询到");
        mailName.setText("");
        mailCode.setText("0");
        mailID1 = "";
    }

    @Override
    public void getsurplusSuccess(BaseModel<MailNumberBean> o, String id) {
        if (o.getData() != null) {
            if (o.getData().getQuantity() > 0) {
                mailCode.setText(o.getData().getQuantity() + "");
                mailCode1 = o.getData().getBranchCode();
                mailID1 = id;
//                mailName.setText(o.getData().getBranchName());
                if (mailDialog != null) {
                    mailDialog.dismiss();
                }
            } else {
                ToastUtils.showShort("未查询到");
                mailCode.setText("0");
                mailID1 = "";
                mailName.setText("");
            }
        } else {
            ToastUtils.showShort("未查询到");
            mailCode.setText("0");
            mailID1 = "";
            mailName.setText("");
        }
    }

    @Override
    public void getofficeSuccess(BaseModel<OfficeBean> o) {
        if (!TextUtils.isEmpty(mCode)) {
            orderid.setText(mCode);
            orderid.setBackgroundResource(R.drawable.et_grey);
        }
        officeBean = o.getData();
        totle_num.setText(officeBean.getCount());
        list4.clear();
        adapter4.clear();
        list3.clear();
        adapter3.clear();
        recyclerView1.setVisibility(View.GONE);
        recyclerView2.setVisibility(View.GONE);
        recyclerView3.setVisibility(View.VISIBLE);
        recyclerView4.setVisibility(View.VISIBLE);
        if ((int) type.getTag() == 0) {
            list3.addAll(officeBean.getList_data());
            adapter3.addAll(list3);
        } else {
            list4.addAll(officeBean.getList_data());
            adapter4.addAll(list4);
        }
        if (officeBean.getList_data().size() > 0) {
            i3 = 0;
            pic3 = officeBean.getList_data().get(0).getImg_base64();
            officedataBean = officeBean.getList_data().get(0);
        }
        handler1.removeMessages(1);
        handler1.sendEmptyMessage(1);
//        playRing("shujuyouxiao.mp3");
    }

    @Override
    public void getonlineOrderSuccess(BaseModel<OnLineOrderBean> o) {
        if (!TextUtils.isEmpty(mCode)) {
            orderid.setText(mCode);
            orderid.setBackgroundResource(R.drawable.et_grey);
        }
        onLineOrderBean = o.getData();
        totle_num.setText(onLineOrderBean.getCount());
        list2.clear();
        adapter2.clear();
        list1.clear();
        adapter1.clear();
        recyclerView1.setVisibility(View.VISIBLE);
        recyclerView2.setVisibility(View.VISIBLE);
        recyclerView3.setVisibility(View.GONE);
        recyclerView4.setVisibility(View.GONE);
        if ((int) type.getTag() == 0) {
            list1.addAll(onLineOrderBean.getList());
            adapter1.addAll(onLineOrderBean.getList());
        } else {
            list2.addAll(onLineOrderBean.getList());
            adapter2.addAll(onLineOrderBean.getList());
        }
        if (onLineOrderBean.getList().size() > 0) {
            i3 = 0;
            listDataBean = onLineOrderBean.getList().get(0);
        }

        handler1.removeMessages(1);
        handler1.sendEmptyMessage(1);
//        playRing("shujuyouxiao.mp3");
    }

    @Override
    public void getKuaiDiImgError() {
        playRing("tuxianghuoqushibai.mp3");
    }

    @Override
    public void getKuaiDiImgSuccess(BaseModel<KuaiDiImgBean> o) {
        if (TextUtils.isEmpty(o.getData().getImg_base64())) {
//            showLoading();
            playRing("tuxianghuoqushibai.mp3");
            handler1.sendEmptyMessageDelayed(5, 3000);
        } else {
            hideLoading();
            playRing("tuxianghuoquchenggong.mp3");
            kuaiDiBean.setImgBase64(o.getData().getImg_base64());
            pic3 = kuaiDiBean.getImgBase64();
            if (imgNull) {
                imgNull = false;
            } else {
                daYin();
            }
        }
    }

    boolean imgNull = false;

    @Override
    public void getKuaiDiCodeSuccess(BaseModel<KuaiDiBean> o) {
        kuaiDiBean = o.getData();
        mail_code1.setText(kuaiDiBean.getKuaidinum());
        shengcheng.setEnabled(false);
        shengcheng.setVisibility(View.INVISIBLE);
//        chanpin_dx.setEnabled(false);
//        lianjie.setEnabled(false);
//        mailName.setEnabled(false);
//        order_type.setEnabled(false);
        playRing("danhaochenggong.mp3");
        if (TextUtils.isEmpty(kuaiDiBean.getImgBase64())) {
            imgNull = true;
//            showLoading();
            handler1.sendEmptyMessageDelayed(5, 3000);
        } else {
            dissmissDialog();
            pic3 = kuaiDiBean.getImgBase64();
        }
        if ((int) dayin_type.getTag() == 1) {
            mPresenter.Into52(officeBean.getList_data().get(i3).getOrder_sn(), mail_code1.getText().toString().trim(), mailID1,
                    sjzl.getText().toString().trim(), chanpin_dx.getText().toString().trim(), officeBean.getList_data().get(i3).getRemarks(),
                    mailName.getText().toString().trim(), ((int) order_type.getTag() + 1) + "");
        } else {
            mPresenter.Into59(officeBean.getList_data().get(i3).getOrder_sn(), mail_code1.getText().toString().trim(), mailID1,
                    sjzl.getText().toString().trim(), chanpin_dx.getText().toString().trim(), officeBean.getList_data().get(i3).getRemarks(),
                    mailName.getText().toString().trim(), ((int) order_type.getTag() + 1) + "");
        }
    }

    @Override
    public void getUpOrderSuccess(BaseModel<String> o) {
        mPresenter.surplus(mailID1);
//        ToastUtil.getInstance()._short(DetailedActivity.this, "操作成功");
//        if ((int) order_type.getTag() == 0) {
//            try {
//                if (!ZPLPrinterHelper.IsOpened()) {
//                    ToastUtil.getInstance()._short(mContext, "打印机连接失败");
//                    return;
//                }
//                if (!dyjStatus) {
//                    ToastUtil.getInstance()._short(mContext, "打印机连接失败");
//                    return;
//                }
//                if (pic3 != null) {
//                    Bitmap bitmap = getBitmap(pic3);
//                    if (TextUtils.isEmpty(MainActivity.userInfoBean.getPrint_paper_width())) {
//                        ToastUtil.getInstance()._short(mContext, "纸张宽度不能为空");
//                        return;
//                    }
//                    if (TextUtils.isEmpty(MainActivity.userInfoBean.getPrint_deviation_x())) {
//                        ToastUtil.getInstance()._short(mContext, "水平偏移不能为空");
//                        return;
//                    }
//                    if (TextUtils.isEmpty(MainActivity.userInfoBean.getPrint_deviation_y())) {
//                        ToastUtil.getInstance()._short(mContext, "垂直偏移不能为空");
//                        return;
//                    }
//                    MainActivity.mZPL.start();
//                    MainActivity.mZPL.PW(MainActivity.userInfoBean.getPrint_paper_width());
//                    MainActivity.mZPL.printBitmap(MainActivity.userInfoBean.getPrint_deviation_x(),
//                            MainActivity.userInfoBean.getPrint_deviation_y(), bitmap);
//                    MainActivity.mZPL.PQ("1", "1", "1", "Y");
//                    int i = MainActivity.mZPL.end();
//                    if (i == 0) {
//                        DayinDialog1 dayinDialog1 = new DayinDialog1(DetailedActivity.this, i + "");
//                        dayinDialog1.show();
//
//                        mPresenter.updateOrder2(officeBean.getList_data().get(i3).getOrder_sn());
//                        chanpin_dx.setText("");
//                        sjzl.setText("");
//                        mail_code1.setText("");
//                        mail_code2.setText("");
//                        getList();
//                        playRing("dayinwancheng.mp3");
//                    } else {
//                        DayinDialog2 dayinDialog2 = new DayinDialog2(DetailedActivity.this, i + "");
//                        dayinDialog2.show();
//                        playRing("shibai.mp3");
//                    }
//                } else {
//                    ToastUtil.getInstance()._short(mContext, "图片为空");
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
    }

    @Override
    public void getupdateOrderSuccess(BaseModel<String> o) {
        shengcheng.setVisibility(View.VISIBLE);
//        chanpin_dx.setEnabled(true);
//        lianjie.setEnabled(true);
//        mailName.setEnabled(true);
//        order_type.setEnabled(true);
        getList();
    }

    @Override
    public void getupdateOrderSuccess2(BaseModel<String> o) {
        shengcheng.setVisibility(View.VISIBLE);
//        chanpin_dx.setEnabled(true);
//        lianjie.setEnabled(true);
//        mailName.setEnabled(true);
//        order_type.setEnabled(true);
        getList();
    }

    MailDialog1 mailDialog;
    String qd_img = "";
    volatile int j = 0;
    List<Integer> list_i = new ArrayList<>();

    @OnClick({R.id.iv_back, R.id.qingkong1, R.id.type, R.id.start_time, R.id.stop_time, R.id.shuaxin, R.id.dayin_img, R.id.dayin_type, R.id.chanpin_dx,
            R.id.lianjie, R.id.order_type, R.id.mailName, R.id.shengcheng, R.id.btn_save, R.id.pic_type})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                AlertDialog.Builder normalDialog = new AlertDialog.Builder(DetailedActivity.this);
                normalDialog.setTitle("提示");
                normalDialog.setMessage("返回主页，当前数据将清除，是否返回");
                normalDialog.setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                });
                normalDialog.setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                normalDialog.create().show();
                break;
            case R.id.qingkong1:
//                chanpin_dx.setEnabled(true);
//                lianjie.setEnabled(true);
//                mailName.setEnabled(true);
//                order_type.setEnabled(true);
                if ((int) type.getTag() == 0 && (int) order_type.getTag() == 1) {
                    shengcheng.setVisibility(View.VISIBLE);
                    chanpin_dx.setText("");
                    sjzl.setText("");
                    mail_code1.setText("");
                    mail_code2.setText("");
                }
                orderid.setText("");
                orderid.setBackgroundResource(R.drawable.et_yellow);
                mCode = "";
                list1.clear();
                list2.clear();
                list3.clear();
                list4.clear();
                adapter1.clear();
                adapter2.clear();
                adapter3.clear();
                adapter4.clear();
                getList();
                playRing("qingkong.mp3");
                break;
            case R.id.start_time:
                MyTimePicker1 myTimePicker1 = new MyTimePicker1();
                Calendar endCalendar;
                if (StringUtils.isEmpty(endTime)) {
                    endCalendar = BaseUtils.dateToCalendar();
                } else {
                    endCalendar = BaseUtils.StringTocalendar(endTime);
                }
                TimePickerView pickerView1 = myTimePicker1.selectTime(DetailedActivity.this,
                        BaseUtils.StringTocalendar("2019-1-1"), endCalendar);
                myTimePicker1.setOnSelectListener(new MyTimePicker1.OnSelectListener() {
                    @Override
                    public void onSelect(Date date, View v) {
                        start_time.setText(BaseUtils.dateToStrLong(date, "yyyy-MM-dd"));
                        getList();
                    }
                });
                pickerView1.show();
                break;
            case R.id.stop_time:
                MyTimePicker1 myTimePicker2 = new MyTimePicker1();
                Calendar endCalendar1;
                if (StringUtils.isEmpty(endTime)) {
                    endCalendar1 = BaseUtils.dateToCalendar();
                } else {
                    endCalendar1 = BaseUtils.StringTocalendar(endTime);
                }
                TimePickerView pickerView2 = myTimePicker2.selectTime(DetailedActivity.this,
                        BaseUtils.StringTocalendar(start_time.getText().toString().trim()), endCalendar1);
                myTimePicker2.setOnSelectListener(new MyTimePicker1.OnSelectListener() {
                    @Override
                    public void onSelect(Date date, View v) {
                        stop_time.setText(BaseUtils.dateToStrLong(date, "yyyy-MM-dd"));
                        getList();
                    }
                });
                pickerView2.show();
                break;
            case R.id.shuaxin:
                shengcheng.setEnabled(true);
                shengcheng.setVisibility(View.VISIBLE);
                chanpin_dx.setText("");
                sjzl.setText("");
                mail_code1.setText("");
                mail_code2.setText("");
                pic3 = "";
                getList();
                break;
            case R.id.btn_save:
                if (officeBean == null) {
                    return;
                }
                if (TextUtils.isEmpty(mail_code2.getText().toString().trim())) {
                    ToastUtil.getInstance()._short(DetailedActivity.this, "快递单号不能为空");
                    return;
                }
                if (TextUtils.isEmpty(mailName.getText().toString().trim())) {
                    ToastUtil.getInstance()._short(DetailedActivity.this, "快递名称不能为空");
                    return;
                }
//                mPresenter.updateOrder(officeBean.getList_data().get(i3).getOrder_sn());
                if ((int) dayin_type.getTag() == 1) {
                    mPresenter.Into52(officeBean.getList_data().get(i3).getOrder_sn(), mail_code2.getText().toString().trim(), mailID1,
                            sjzl.getText().toString().trim(), chanpin_dx.getText().toString().trim(), officeBean.getList_data().get(i3).getRemarks(),
                            mailName.getText().toString().trim(), ((int) order_type.getTag() + 1) + "");
                } else {
                    mPresenter.Into59(officeBean.getList_data().get(i3).getOrder_sn(), mail_code2.getText().toString().trim(), mailID1,
                            sjzl.getText().toString().trim(), chanpin_dx.getText().toString().trim(), officeBean.getList_data().get(i3).getRemarks(),
                            mailName.getText().toString().trim(), ((int) order_type.getTag() + 1) + "");
                }
                break;
            case R.id.dayin_img:
                if (!ZPLPrinterHelper.IsOpened()) {
                    ToastUtil.getInstance()._short(mContext, "打印机连接失败");
                    return;
                }
                if (!dyjStatus) {
                    ToastUtil.getInstance()._short(mContext, "打印机连接失败");
                    return;
                }
//                LogUtils.e("dayin_img.setEnabled(false);");
//                dayin_img.setEnabled(false);
                try {
                    if ((int) dayin_type.getTag() == 0) {
                        if ((int) type.getTag() == 0) {
                            showLoading();
                            list_i.clear();
                            j = 0;
                            if (onLineOrderBean.getList().size() > 0)
                                new Thread(thread).start();
//                            handler1.post(dyRunnable);

//                            new Thread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    try {
//                                        List<Integer> list_i = new ArrayList<>();
//                                        for (int j = 0; j < onLineOrderBean.getList().size(); j++) {
//                                            String qd_img = "";
//                                            if ((int) type.getTag() == 0) {
//                                                qd_img = onLineOrderBean.getList().get(j).getQd_image();
//                                            } else {
//                                                if ((int) pic_type.getTag() == 0) {
//                                                    qd_img = onLineOrderBean.getList().get(j).getQd_image();
//                                                } else {
//                                                    qd_img = onLineOrderBean.getList().get(j).getQd_images_two();
//                                                }
//                                            }
//                                            if (!TextUtils.isEmpty(qd_img)) {
//                                                Bitmap bitmap = GlideImageLoader.getBitmap(BaseUrl.url2 + qd_img);
//                                                if (TextUtils.isEmpty(MainActivity.userInfoBean.getPrint_paper_width())) {
//                                                    ToastUtil.getInstance()._short(mContext, "纸张宽度不能为空");
//                                                    return;
//                                                }
//                                                if (TextUtils.isEmpty(MainActivity.userInfoBean.getPrint_deviation_x())) {
//                                                    ToastUtil.getInstance()._short(mContext, "水平偏移不能为空");
//                                                    return;
//                                                }
//                                                if (TextUtils.isEmpty(MainActivity.userInfoBean.getPrint_deviation_y())) {
//                                                    ToastUtil.getInstance()._short(mContext, "垂直偏移不能为空");
//                                                    return;
//                                                }
//                                                MainActivity.mZPL.start();
////                                                if ((int) type.getTag() == 0) {
////                                                    MainActivity.mZPL.WriteData(("^LL " + onLineOrderBean.getList().get(j).getQd_image_height()).getBytes());
////                                                } else {
////                                                    if ((int) pic_type.getTag() == 0) {
////                                                        MainActivity.mZPL.WriteData(("^LL " + onLineOrderBean.getList().get(j).getQd_image_height()).getBytes());
////                                                    } else {
////                                                        MainActivity.mZPL.WriteData(("^LL " + onLineOrderBean.getList().get(j).getQd_image_two_height()).getBytes());
////                                                    }
////                                                }
//                                                MainActivity.mZPL.PW(MainActivity.userInfoBean.getPrint_paper_width());
//                                                MainActivity.mZPL.printBitmap(MainActivity.userInfoBean.getPrint_deviation_x(),
//                                                        MainActivity.userInfoBean.getPrint_deviation_y(), bitmap);
//                                                MainActivity.mZPL.PQ("1", "1", "1", "Y");
//                                                int i = MainActivity.mZPL.end();
//                                                LogUtils.e("打印返回：" + i);
//
//                                                if (i == 0) {
//                                                    list_i.add(0);
////                                                    ToastUtils.showShort("打印成功");
//                                                    mPresenter.updateOrder1(onLineOrderBean.getList().get(j).getOrder_sn());
//                                                } else {
////                                                    ToastUtils.showShort("打印失败");
//                                                    list_i.add(1);
//                                                }
//                                            } else {
////                                                ToastUtil.getInstance()._short(mContext, "未获取到图片，请先去生成");
//                                                list_i.add(1);
//                                            }
//                                        }
//                                        Looper.prepare();
//                                        DayinDialog3 dayinDialog = new DayinDialog3(DetailedActivity.this, list_i);
//                                        dayinDialog.show();
//                                        Looper.loop();
//                                        playRing("dayinwancheng.mp3");
//                                    } catch (Exception e) {
//                                        e.printStackTrace();
//                                    }
//                                }
//                            }).start();

//                    LogUtils.e(System.currentTimeMillis());
                        } else {
                            if (listDataBean == null) {
//                                dayin_img.setEnabled(true);
                                ToastUtils.showShort("请选择打印的图片");
                                return;
                            }
                            qd_img = "";
                            if ((int) type.getTag() == 0) {
                                qd_img = listDataBean.getQd_image();
                            } else {
                                if ((int) pic_type.getTag() == 0) {
                                    qd_img = listDataBean.getQd_image();
                                } else {
                                    qd_img = listDataBean.getQd_images_two();
                                }
                            }
                            if (!TextUtils.isEmpty(qd_img)) {
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
//                                    List<Integer> list_i = new ArrayList<>();
//                                    for (int j = 0; j < onLineOrderBean.getList().size(); j++) {
                                            Bitmap bitmap = GlideImageLoader.getBitmap(BaseUrl.url2 + qd_img);
                                            if (TextUtils.isEmpty(MainActivity.userInfoBean.getPrint_paper_width())) {
//                                                dayin_img.setEnabled(true);
                                                ToastUtil.getInstance()._short(mContext, "纸张宽度不能为空");
                                                return;
                                            }
                                            if (TextUtils.isEmpty(MainActivity.userInfoBean.getPrint_deviation_x())) {
//                                                dayin_img.setEnabled(true);
                                                ToastUtil.getInstance()._short(mContext, "水平偏移不能为空");
                                                return;
                                            }
                                            if (TextUtils.isEmpty(MainActivity.userInfoBean.getPrint_deviation_y())) {
//                                                dayin_img.setEnabled(true);
                                                ToastUtil.getInstance()._short(mContext, "垂直偏移不能为空");
                                                return;
                                            }
                                            MainActivity.mZPL.start();
//                                            if ((int) type.getTag() == 0) {
//                                                MainActivity.mZPL.WriteData(("^LL " + listDataBean.getQd_image_height()).getBytes());
//                                            } else {
//                                                if ((int) pic_type.getTag() == 0) {
//                                                    MainActivity.mZPL.WriteData(("^LL " + listDataBean.getQd_image_height()).getBytes());
//                                                } else {
//                                                    MainActivity.mZPL.WriteData(("^LL " + listDataBean.getQd_image_two_height()).getBytes());
//                                                }
//                                            }
                                            MainActivity.mZPL.printData("^LL" + bitmap.getHeight() + "\r\n");
                                            MainActivity.mZPL.PW(MainActivity.userInfoBean.getPrint_paper_width());
                                            MainActivity.mZPL.printBitmap(MainActivity.userInfoBean.getPrint_deviation_x(),
                                                    MainActivity.userInfoBean.getPrint_deviation_y(), bitmap);

                                            MainActivity.mZPL.PQ("1", "1", "1", "Y");

                                            int i = MainActivity.mZPL.end();
                                            System.out.println("打印返回：" + i);
                                            Looper.prepare();
//                                            dayin_img.setEnabled(true);
                                            if (i == 0) {
                                                DayinDialog1 dayinDialog1 = new DayinDialog1(DetailedActivity.this, i + "");
                                                dayinDialog1.show();
                                                dayinDialog1.setOnDismissListener(new DialogInterface.OnDismissListener() {
                                                    @Override
                                                    public void onDismiss(DialogInterface dialog) {
                                                        handler1.sendEmptyMessage(3);
                                                    }
                                                });
                                                playRing("dayinwancheng.mp3");
                                            } else {
                                                DayinDialog2 dayinDialog2 = new DayinDialog2(DetailedActivity.this, i + "");
                                                dayinDialog2.show();
                                                playRing("dayinshibai.mp3");
                                            }
                                            Looper.loop();


//                                    }
//                                    Looper.prepare();
//                                    DayinDialog3 dayinDialog = new DayinDialog3(DetailedActivity.this, list_i);
//                                    dayinDialog.show();
//                                    Looper.loop();
//                                    playRing("dayinwancheng.mp3");
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }).start();
                            } else {
                                ToastUtil.getInstance()._short(mContext, "未获取到图片，请先去生成");
//                                            list_i.add(1);
                            }
                        }

                    } else {
//                        if ((int) type.getTag() == 0) {
//                        pic3 = "";
                        if (!TextUtils.isEmpty(pic3)) {
                            daYin();
                        } else {
                            if (kuaiDiBean != null) {
                                showLoading();
                                mPresenter.getKuaiDiImg(((int) dayin_type.getTag() + 1) + "", officedataBean.getOrder_sn(), kuaiDiBean.getKuaidinum());
                            }
//                            dayin_img.setEnabled(true);
                            ToastUtil.getInstance()._short(mContext, "图片为空");
                        }
//                        } else {
//                            new Thread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    try {
//                                        List<Integer> list_i = new ArrayList<>();
//                                        for (int j = 0; j < officeBean.getList_data().size(); j++) {
//                                            if (officeBean.getList_data().get(j).getImg_base64() != null) {
//                                                Bitmap bitmap = GlideImageLoader.getBitmap(BaseUrl.url1 + officeBean.getList_data().get(j).getImg_base64());
//                                                if (TextUtils.isEmpty(MainActivity.userInfoBean.getPrint_paper_width())) {
//                                                    ToastUtil.getInstance()._short(mContext, "纸张宽度不能为空");
//                                                    return;
//                                                }
//                                                if (TextUtils.isEmpty(MainActivity.userInfoBean.getPrint_deviation_x())) {
//                                                    ToastUtil.getInstance()._short(mContext, "水平偏移不能为空");
//                                                    return;
//                                                }
//                                                if (TextUtils.isEmpty(MainActivity.userInfoBean.getPrint_deviation_y())) {
//                                                    ToastUtil.getInstance()._short(mContext, "垂直偏移不能为空");
//                                                    return;
//                                                }
//                                                MainActivity.mZPL.start();
//                                                MainActivity.mZPL.PW(MainActivity.userInfoBean.getPrint_paper_width());
//                                                MainActivity.mZPL.printBitmap(MainActivity.userInfoBean.getPrint_deviation_x(),
//                                                        MainActivity.userInfoBean.getPrint_deviation_y(), bitmap);
//                                                MainActivity.mZPL.PQ("1", "1", "1", "Y");
//
//                                                int i = MainActivity.mZPL.end();
//                                                System.out.println("打印返回：" + i);
//                                                if (i == 0) {
//                                                    list_i.add(0);
//                                                    if((int)dayin_type.getTag() == 1) {
//                                                        mPresenter.updateOrder2(officeBean.getList_data().get(j).getOrder_sn());
//                                                    }else{
//                                                        mPresenter.updateOrder3(officeBean.getList_data().get(j).getOrder_sn());
//                                                    }
//
//                                                } else {
//                                                    list_i.add(1);
//                                                }
//                                            } else {
//                                                list_i.add(1);
//                                            }
//                                        }
//                                        Looper.prepare();
//                                        DayinDialog3 dayinDialog = new DayinDialog3(DetailedActivity.this, list_i);
//                                        dayinDialog.show();
//                                        playRing("dayinwancheng.mp3");
//                                        Looper.loop();
//                                    } catch (Exception e) {
//                                        e.printStackTrace();
//                                    }
//                                }
//                            }).start();
//
//                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.chanpin_dx:
                ChiCunDialog1 chiCunDialog = new ChiCunDialog1(DetailedActivity.this, chanpin_dx);
                chiCunDialog.show();
                break;
            case R.id.lianjie:
                EditDialog1 editDialog = new EditDialog1(DetailedActivity.this, sjzl);
                editDialog.show();
                handler1.removeCallbacks(runnable);
                break;
            case R.id.mailName:
                if ((int) order_type.getTag() == 0) {
                    if (mailList1.size() > 0) {
                        mailDialog = null;
                        mailDialog = new MailDialog1(DetailedActivity.this, mailList1, mailName, mailCode, mPresenter);
                        mailDialog.show();
                    }
                } else {
                    if (mailList.size() > 0) {
                        mailDialog = null;
                        mailDialog = new MailDialog1(DetailedActivity.this, mailList, mailName, mailCode);
                        mailDialog.show();
                    }
                }
                break;
            case R.id.shengcheng:
                if (officedataBean == null) {
                    ToastUtil.getInstance()._short(DetailedActivity.this, "选择为空");
                    return;
                }
                String name;
                String phone;
                String address;
                String remake;
                if ((int) dayin_type.getTag() == 2) {
                    name = officedataBean.getShop_sh_name();
                    phone = officedataBean.getShop_sh_phone();
                    address = officedataBean.getShop_sh_address();
                    remake = officedataBean.getDetails();
                } else {
                    name = officedataBean.getName();
                    phone = officedataBean.getPhone();
                    address = officedataBean.getProvince() + officedataBean.getCity() +
                            officedataBean.getArea() + officedataBean.getAddress();
                    remake = officedataBean.getRemarks();
                }

                if (TextUtils.isEmpty(name)) {
                    ToastUtil.getInstance()._short(DetailedActivity.this, "收件人信息不能为空");
                    return;
                }


                if (TextUtils.isEmpty(phone)) {
                    ToastUtil.getInstance()._short(DetailedActivity.this, "收件人信息不能为空");
                    return;
                }

                if (TextUtils.isEmpty(address)) {
                    ToastUtil.getInstance()._short(DetailedActivity.this, "收件人信息不能为空");
                    return;
                }
                if (TextUtils.isEmpty(sjzl.getText().toString().trim().replace("g", ""))) {
                    ToastUtil.getInstance()._short(DetailedActivity.this, "实际重量不能为空");
                    return;
                }
                if (StringUtils.equalsIgnoreCase(sjzl.getText().toString().trim().replace("g",
                        ""), "0")) {
                    ToastUtil.getInstance()._short(DetailedActivity.this, "实际重量不能为空");
                    return;
                }
                if (TextUtils.isEmpty(templateCode)) {
                    ToastUtil.getInstance()._short(DetailedActivity.this, "请前往后台完善" + mailName.getText().toString().trim() + "信息");
                    return;
                }
                if (TextUtils.isEmpty(mailID1)) {
                    ToastUtil.getInstance()._short(DetailedActivity.this, "快递公司编码不能为空");
                    return;
                }
                if (TextUtils.isEmpty(officedataBean.getOrder_id())) {
                    ToastUtil.getInstance()._short(DetailedActivity.this, "订单ID不能为空");
                    return;
                }
                if (TextUtils.isEmpty(mailName.getText().toString().trim())) {
                    ToastUtil.getInstance()._short(DetailedActivity.this, "快递名称不能为空");
                    return;
                }

                shengcheng.setVisibility(View.INVISIBLE);
                showLoading();
                mPresenter.getKuaiDiCode(name, phone, address, "1", sjzl.getText().toString().trim().replace("g",
                        ""), mailName.getText().toString().trim(), remake, templateCode,
                        (((int) dayin_type.getTag()) + 1) + "", officedataBean.getOrder_id(), mailID1);
                break;
            case R.id.dayin_type:
                XPopup.get(DetailedActivity.this).asCenterList("请选择类型", new String[]{"线上清单", "办公邮寄", "售后邮寄"},
                        // null, /** 图标Id数组，可无 **/
                        // 1,    /** 选中的position，默认没有选中效果 **/
                        new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text) {
//                                if (position == 2) {
//                                    ToastUtil.getInstance()._short(DetailedActivity.this, "暂无售后邮寄");
//                                    return;
//                                }
                                dayin_type.setText(text);
                                dayin_type.setTag(position);
                                list1.clear();
                                adapter1.clear();
                                list2.clear();
                                adapter2.clear();
                                list3.clear();
                                adapter3.clear();
                                list4.clear();
                                adapter4.clear();
                                shengcheng.setVisibility(View.VISIBLE);
                                if (position == 0) {
                                    ll.setVisibility(View.GONE);
                                    recyclerView1.setVisibility(View.VISIBLE);
                                    recyclerView2.setVisibility(View.VISIBLE);
                                    recyclerView3.setVisibility(View.GONE);
                                    recyclerView4.setVisibility(View.GONE);
                                    btn_save.setVisibility(View.GONE);
                                    dayin_img.setVisibility(View.VISIBLE);
                                    tuxiang.setText("图像");
                                    if ((int) type.getTag() == 0) {
                                        pic_type_ll.setVisibility(View.GONE);
                                    } else {
                                        pic_type_ll.setVisibility(View.VISIBLE);
                                    }
                                } else {
                                    pic_type_ll.setVisibility(View.GONE);
                                    if ((int) type.getTag() == 0) {
                                        ll.setVisibility(View.VISIBLE);
                                        if ((int) order_type.getTag() == 0) {
                                            btn_save.setVisibility(View.GONE);
                                            dayin_img.setVisibility(View.VISIBLE);
                                        } else {
                                            btn_save.setVisibility(View.VISIBLE);
                                            dayin_img.setVisibility(View.GONE);
                                        }
                                        tuxiang.setText("内容");
                                    } else {
                                        ll.setVisibility(View.GONE);
                                        btn_save.setVisibility(View.GONE);
                                        dayin_img.setVisibility(View.VISIBLE);
                                        tuxiang.setText("图像");
                                    }
                                    recyclerView1.setVisibility(View.GONE);
                                    recyclerView2.setVisibility(View.GONE);
                                    recyclerView3.setVisibility(View.VISIBLE);
                                    recyclerView4.setVisibility(View.VISIBLE);
                                }
                                getList();
                            }
                        }).show();
                break;
            case R.id.type:
                XPopup.get(DetailedActivity.this).asCenterList("请选择类型", new String[]{"未打印", "已打印"}, new OnSelectListener() {
                    @Override
                    public void onSelect(int position, String text) {
                        type.setText(text);
                        type.setTag(position);
                        list1.clear();
                        adapter1.clear();
                        list2.clear();
                        adapter2.clear();
                        list3.clear();
                        adapter3.clear();
                        list4.clear();
                        adapter4.clear();
                        if ((int) dayin_type.getTag() == 0) {
                            if (position == 0) {
                                start_time_ll.setVisibility(View.GONE);
                                stop_time_ll.setVisibility(View.GONE);
                                weidayin_ll.setVisibility(View.VISIBLE);
                                yidayin_ll.setVisibility(View.GONE);
                                pic_type_ll.setVisibility(View.GONE);
                                tuxiang.setText("图像");
                            } else {
                                start_time_ll.setVisibility(View.VISIBLE);
                                stop_time_ll.setVisibility(View.VISIBLE);
                                weidayin_ll.setVisibility(View.GONE);
                                yidayin_ll.setVisibility(View.VISIBLE);
                                pic_type_ll.setVisibility(View.VISIBLE);
                                tuxiang.setText("图像");
                            }
                            btn_save.setVisibility(View.GONE);
                            dayin_img.setVisibility(View.VISIBLE);
                        } else {
                            pic_type_ll.setVisibility(View.GONE);
                            if (position == 0) {
                                start_time_ll.setVisibility(View.GONE);
                                stop_time_ll.setVisibility(View.GONE);
                                weidayin_ll.setVisibility(View.VISIBLE);
                                yidayin_ll.setVisibility(View.GONE);
                                ll.setVisibility(View.VISIBLE);
                                tuxiang.setText("内容");
                                if ((int) order_type.getTag() == 0) {
                                    btn_save.setVisibility(View.GONE);
                                    dayin_img.setVisibility(View.VISIBLE);
                                } else {
                                    btn_save.setVisibility(View.VISIBLE);
                                    dayin_img.setVisibility(View.GONE);
                                }
                            } else {
                                start_time_ll.setVisibility(View.VISIBLE);
                                stop_time_ll.setVisibility(View.VISIBLE);
                                weidayin_ll.setVisibility(View.GONE);
                                yidayin_ll.setVisibility(View.VISIBLE);
                                ll.setVisibility(View.GONE);
                                btn_save.setVisibility(View.GONE);
                                dayin_img.setVisibility(View.VISIBLE);
                                tuxiang.setText("图像");
                            }
                        }
                        getList();
                    }
                }).show();
                break;
            case R.id.order_type:
                XPopup.get(DetailedActivity.this).asCenterList("请选择单号方式", new String[]{"自动生成", "手动填写"},
                        new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text) {
                                order_type.setText(text);
                                order_type.setTag(position);
                                if (position == 0) {
                                    mail_code_ll1.setVisibility(View.VISIBLE);
                                    mail_code_ll2.setVisibility(View.GONE);
                                    btn_save.setVisibility(View.GONE);
                                    dayin_img.setVisibility(View.VISIBLE);
                                    for (int i = 0; i < mailList1.size(); i++) {
                                        if (MyApplication.getMailID().equals(mailList1.get(i).getId())) {
                                            mailName.setText(mailList1.get(i).getSon_name());
                                            mailCode1 = mailList1.get(i).getCode();
                                            mailID1 = mailList1.get(i).getId();
                                            templateCode = mailList1.get(i).getTemplate_code();
                                            mPresenter.surplus(mailList1.get(i).getId());
                                            return;
                                        }
                                        if (i == mailList1.size() - 1) {
                                            mailName.setText(mailList1.get(0).getSon_name());
                                            mailCode1 = mailList1.get(0).getCode();
                                            mailID1 = mailList1.get(0).getId();
                                            templateCode = mailList1.get(0).getTemplate_code();
                                            mPresenter.surplus(mailList1.get(0).getId());
                                        }
                                    }
                                } else {
                                    mail_code_ll1.setVisibility(View.GONE);
                                    mail_code_ll2.setVisibility(View.VISIBLE);
                                    if ((int) type.getTag() == 0) {
                                        btn_save.setVisibility(View.VISIBLE);
                                        dayin_img.setVisibility(View.GONE);
                                    } else {
                                        btn_save.setVisibility(View.GONE);
                                        dayin_img.setVisibility(View.GONE);
                                    }
                                    for (int i = 0; i < mailList.size(); i++) {
                                        if (MyApplication.getMailCode().equals(mailList.get(i).getId())) {
                                            mailName.setText(mailList.get(i).getName());
                                            mailCode.setText(mailList.get(i).getCode());
                                            mailCode1 = mailList.get(i).getCode();
                                            mailID1 = mailList.get(i).getId();
                                            return;
                                        }
                                        if (i == mailList.size() - 1) {
                                            mailName.setText(mailList.get(0).getName());
                                            mailCode.setText(mailList.get(0).getCode());
                                            mailCode1 = mailList.get(0).getCode();
                                            mailID1 = mailList.get(0).getId();
                                        }
                                    }
                                }
                            }
                        }).show();
                break;
            case R.id.pic_type:
                XPopup.get(DetailedActivity.this).asCenterList("请选择图片类型", new String[]{"第一张", "第二张"},
                        new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text) {
                                pic_type.setText(text);
                                pic_type.setTag(position);
                            }
                        }).show();
                break;
        }
    }

    Runnable thread = new Runnable() {
        @Override
        public void run() {
            try {
//                List<Integer> list_i = new ArrayList<>();
//                for (int j = 0; j < onLineOrderBean.getList().size(); j++) {
                String qd_img = "";
                if ((int) type.getTag() == 0) {
                    qd_img = onLineOrderBean.getList().get(j).getQd_image();
                } else {
                    if ((int) pic_type.getTag() == 0) {
                        qd_img = onLineOrderBean.getList().get(j).getQd_image();
                    } else {
                        qd_img = onLineOrderBean.getList().get(j).getQd_images_two();
                    }
                }
                if (!TextUtils.isEmpty(qd_img)) {
                    Bitmap bitmap = GlideImageLoader.getBitmap(BaseUrl.url2 + qd_img);
                    if (TextUtils.isEmpty(MainActivity.userInfoBean.getPrint_paper_width())) {
                        ToastUtil.getInstance()._short(mContext, "纸张宽度不能为空");
                        return;
                    }
                    if (TextUtils.isEmpty(MainActivity.userInfoBean.getPrint_deviation_x())) {
                        ToastUtil.getInstance()._short(mContext, "水平偏移不能为空");
                        return;
                    }
                    if (TextUtils.isEmpty(MainActivity.userInfoBean.getPrint_deviation_y())) {
                        ToastUtil.getInstance()._short(mContext, "垂直偏移不能为空");
                        return;
                    }
                    MainActivity.mZPL.start();
//                                                if ((int) type.getTag() == 0) {
//                                                    MainActivity.mZPL.WriteData(("^LL " + onLineOrderBean.getList().get(j).getQd_image_height()).getBytes());
//                                                } else {
//                                                    if ((int) pic_type.getTag() == 0) {
//                                                        MainActivity.mZPL.WriteData(("^LL " + onLineOrderBean.getList().get(j).getQd_image_height()).getBytes());
//                                                    } else {
//                                                        MainActivity.mZPL.WriteData(("^LL " + onLineOrderBean.getList().get(j).getQd_image_two_height()).getBytes());
//                                                    }
//                                                }
                    MainActivity.mZPL.printData("^LL" + bitmap.getHeight() + "\r\n");
                    MainActivity.mZPL.PW(MainActivity.userInfoBean.getPrint_paper_width());
                    MainActivity.mZPL.printBitmap(MainActivity.userInfoBean.getPrint_deviation_x(),
                            MainActivity.userInfoBean.getPrint_deviation_y(), bitmap);
                    MainActivity.mZPL.PQ("1", "1", "1", "Y");
                    int i = MainActivity.mZPL.end();
                    LogUtils.e("打印返回：" + i);
//                    Looper.prepare();
                    if (i == 0) {
                        list_i.add(0);
                        playRing("dayinwancheng.mp3");
//                                                    ToastUtils.showShort("打印成功");
                        mPresenter.updateOrder1(onLineOrderBean.getList().get(j).getOrder_sn());
                    } else {
//                                                    ToastUtils.showShort("打印失败");
//                DayinDialog3 dayinDialog = new DayinDialog3(DetailedActivity.this, list_i);
//                dayinDialog.show();

                        playRing("dayinshibai.mp3");
                        handler1.sendEmptyMessageDelayed(7, 2000);
                        list_i.add(1);
                    }
//                    Looper.loop();
                } else {
//                                                ToastUtil.getInstance()._short(mContext, "未获取到图片，请先去生成");
//                    Looper.prepare();
                    playRing("dayinshibai.mp3");
                    handler1.sendEmptyMessageDelayed(7, 2000);
                    list_i.add(1);
//                    Looper.loop();
                }
//                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    public void daYin() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = GlideImageLoader.getBitmap(BaseUrl.url1 + pic3);
                if (TextUtils.isEmpty(MainActivity.userInfoBean.getPrint_paper_width())) {
//                    dayin_img.setEnabled(true);
                    ToastUtil.getInstance()._short(mContext, "纸张宽度不能为空");
                    return;
                }
                if (TextUtils.isEmpty(MainActivity.userInfoBean.getPrint_deviation_x())) {
//                    dayin_img.setEnabled(true);
                    ToastUtil.getInstance()._short(mContext, "水平偏移不能为空");
                    return;
                }
                if (TextUtils.isEmpty(MainActivity.userInfoBean.getPrint_deviation_y())) {
//                    dayin_img.setEnabled(true);
                    ToastUtil.getInstance()._short(mContext, "垂直偏移不能为空");
                    return;
                }
                int i = -1;
                try {
                    MainActivity.mZPL.start();
                    MainActivity.mZPL.printData("^LL" + bitmap.getHeight() + "\r\n");
                    MainActivity.mZPL.PW(MainActivity.userInfoBean.getPrint_paper_width());
                    MainActivity.mZPL.printBitmap(MainActivity.userInfoBean.getPrint_deviation_x(),
                            MainActivity.userInfoBean.getPrint_deviation_y(), bitmap);
                    MainActivity.mZPL.PQ("1", "1", "1", "Y");
                    i = MainActivity.mZPL.end();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Looper.prepare();
//                dayin_img.setEnabled(true);
                if (i == 0) {
                    DayinDialog1 dayinDialog1 = new DayinDialog1(DetailedActivity.this, i + "");
                    dayinDialog1.show();
                    dayinDialog1.setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            handler1.sendEmptyMessage(4);
                        }
                    });
                    playRing("dayinwancheng.mp3");
                } else {
                    DayinDialog2 dayinDialog2 = new DayinDialog2(DetailedActivity.this, i + "");
                    dayinDialog2.show();
                    playRing("dayinshibai.mp3");
//                                            dayinDialog2.setOnDismissListener(new DialogInterface.OnDismissListener() {
//                                                @Override
//                                                public void onDismiss(DialogInterface dialog) {
//                                                    shengcheng.setEnabled(true);
//                                                    chanpin_dx.setText("");
//                                                    sjzl.setText("");
//                                                    mail_code1.setText("");
//                                                    mail_code2.setText("");
//                                                    if ((int) dayin_type.getTag() == 1) {
//                                                        mPresenter.updateOrder2(officeBean.getList_data().get(i3).getOrder_sn());
//                                                    } else {
//                                                        mPresenter.updateOrder3(officeBean.getList_data().get(i3).getOrder_sn());
//                                                    }
//                                                }
//                                            });
                }
                Looper.loop();

            }
        }).start();
    }

    @Override
    public void onUpFail(String mag) {
        dissmissDialog();
        if (mag.equals("1")) {
            shengcheng.setEnabled(true);
            shengcheng.setVisibility(View.VISIBLE);
            MyDialogUtil.showDialog(this, "单号生成失败");
            playRing("danhaoshibai.mp3");
            return;
        }
        MyDialogUtil.showDialog(this, mag);
//        playRing("danhaoshibai.mp3");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            AlertDialog.Builder normalDialog = new AlertDialog.Builder(DetailedActivity.this);
            normalDialog.setTitle("提示");
            normalDialog.setMessage("返回主页，当前数据将清除，是否返回");
            normalDialog.setPositiveButton("是", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    finish();
                }
            });
            normalDialog.setNegativeButton("否", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            normalDialog.create().show();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }

    }

    AidcManager manager;
    BarcodeReader barcodeReader;

    private void initScan() {
        //第一步：获取扫描资源，设置扫描参数，开启扫描功能
        AidcManager.create(DetailedActivity.this, new AidcManager.CreatedCallback() {
            @Override
            public void onCreated(AidcManager aidcManager) {
                manager = aidcManager;
                barcodeReader = manager.createBarcodeReader();
                try {
                    barcodeReader.claim(); //开启扫描功能
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //第二步：添加侧面扫描键事件监听和条码事件监听
                barcodeReader.addTriggerListener(DetailedActivity.this);
                barcodeReader.addBarcodeListener(DetailedActivity.this);
            }
        });
    }

    @Override
    public void onBarcodeEvent(BarcodeReadEvent barcodeReadEvent) {
        String barcodeData = barcodeReadEvent.getBarcodeData();
        System.out.println("扫码数据：" + barcodeData);
        if (!TextUtils.isEmpty(barcodeData)) {
            mCode = barcodeData;
            getList();
        }
    }

    @Override
    public void onFailureEvent(BarcodeFailureEvent barcodeFailureEvent) {
        System.out.println("失败：");
    }

    @Override
    public void onTriggerEvent(TriggerStateChangeEvent triggerStateChangeEvent) {
        System.out.println("按键：");
        if (triggerStateChangeEvent.getState() == true) {
            try {
                barcodeReader.light(true);        //开启补光
                barcodeReader.aim(true);        //开启瞄准线
                barcodeReader.decode(true);        //开启解码
            } catch (Exception e) {
                Toast.makeText(DetailedActivity.this, "开启扫描失败", Toast.LENGTH_SHORT).show();
            }
        } else if (triggerStateChangeEvent.getState() == false) {
            try {
                barcodeReader.light(false);        //关闭补光
                barcodeReader.aim(false);        //关闭瞄准线
                barcodeReader.decode(false);    //关闭解码
            } catch (Exception e) {
                Toast.makeText(DetailedActivity.this, "关闭扫描失败", Toast.LENGTH_SHORT).show();
            }
        }
    }


    private AssetManager assetManager;
    private MediaPlayer player = new MediaPlayer();

    private void playRing(String fileName) {
        try {
            assetManager = getAssets();
            AssetFileDescriptor fileDescriptor = assetManager.openFd(fileName);
//            if (player.isPlaying()) {
            player.reset();
//            }
            player.setDataSource(fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(),
                    fileDescriptor.getLength());
            player.prepare();
            player.start();
            player.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
                @Override
                public void onSeekComplete(MediaPlayer mp) {
                    player.stop();
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void playUrl(String fileName, final int i) {
        if (TextUtils.isEmpty(fileName)) {
            if (i == 1) {
                playRing("luruchenggong.mp3");
                return;
            } else {
                playRing("wuxiao.mp3");
                return;
            }
        }
        try {
            player.reset();
            if (!fileName.contains("http")) {
                player.setDataSource(BaseUrl.mp3Url + fileName);
            } else {
                player.setDataSource(fileName);
            }
            player.prepare();
            player.start();
            player.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
                @Override
                public void onSeekComplete(MediaPlayer mp) {
                    if (i == 1) {
                        playRing("luruchenggong.mp3");
                    } else {
                        playRing("wuxiao.mp3");
                    }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (barcodeReader != null) {
            try {
                barcodeReader.claim();        //开启扫描功能
            } catch (Exception e) {
//                Toast.makeText(this, "开启扫描失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (barcodeReader != null) {
            barcodeReader.release();        //释放扫描资源
        }
    }

    @Override
    public void onDestroy() {
        if (bleScale != null) {
            bleScale.removeOnConnectListener(onConnectListener);
        }
        if (btScale != null) {
            btScale.removeOnConnectBlueListener(onConnectBlueListener);
            btScale.removeOnReceivedDataListener(onReceivedDataListener);
        }
        handler1.removeCallbacksAndMessages(null);
        super.onDestroy();
        if (barcodeReader != null) {
            barcodeReader.removeBarcodeListener(this);
            barcodeReader.removeTriggerListener(this);
            barcodeReader.close();
        }
        if (manager != null) {
            manager.close();
        }
        handler1.removeMessages(1);
    }

    public void getDayinStatus() {
        try {

            MainActivity.mZPL.WriteData("~HQES\r\n".getBytes());
            String str = byteToString(MainActivity.mZPL.ReadData(2)).replace("PRINTER STATUS ERROR:", "");
            if (str.length() > 0 && str.substring(0, 1).equals("0")) {
                dyjStatus = true;
                dayin_img.setImageResource(R.mipmap.dayin_true);
                if ((MyApplication.isDyPlay == 0 || MyApplication.isDyPlay == 2) && !MyApplication.dy_scaleIsConnect) {
                    MyApplication.isDyPlay = 1;
                    MyApplication.dy_scaleIsConnect = true;
                    playRing("lianjiesuccess.mp3");
                }
            } else {
                dyjStatus = false;
                dayin_img.setImageResource(R.mipmap.dayin_false);
                if ((MyApplication.isDyPlay == 1) && MyApplication.dy_scaleIsConnect) {
                    MyApplication.isDyPlay = 2;
                    MyApplication.dy_scaleIsConnect = false;
                    playRing("lianjieerror.mp3");
                }
            }
        } catch (Exception e) {
//            handler1.removeMessages(1);
//            dyjStatus = false;
//            dayin_img.setImageResource(R.mipmap.dayin_false);
//            if ((MyApplication.isDyPlay == 1) && MyApplication.dy_scaleIsConnect) {
//                MyApplication.isDyPlay = 2;
//                MyApplication.dy_scaleIsConnect = false;
//                playRing("lianjieerror.mp3");
//            }
            e.printStackTrace();
        }
    }

    private static String byteToString(byte[] bytes) {
        if (null == bytes || bytes.length == 0) {
            return "";
        }
        String strContent = "";
        try {
            strContent = new String(bytes, "utf-8");
        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
        }
        return strContent;
    }

    public static Bitmap setImage(String imageStr) {
        byte[] decode = Base64.decode(imageStr, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(decode, 0, decode.length);
    }

    public String getTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(System.currentTimeMillis());
        return formatter.format(date);
    }

    public void getList() {
        if ((int) dayin_type.getTag() == 0) {
            if ((int) type.getTag() == 0) {
                mPresenter.onlineOrder(mCode, type.getTag().toString(), "", "");
            } else {
                if (!TextUtils.isEmpty(start_time.getText().toString().trim())) {
                    if (TextUtils.isEmpty(stop_time.getText().toString().trim())) {
                        mPresenter.onlineOrder(mCode, type.getTag().toString(), start_time.getText().toString().trim() + " 00:00:00",
                                start_time.getText().toString().trim() + " 23:59:59");
                    } else {
                        mPresenter.onlineOrder(mCode, type.getTag().toString(), start_time.getText().toString().trim() + " 00:00:00",
                                stop_time.getText().toString().trim() + " 23:59:59");
                    }
                }
            }
        } else if ((int) dayin_type.getTag() == 1) {
            if ((int) type.getTag() == 0) {
                mPresenter.office(mCode, type.getTag().toString(), "", "");
            } else {
                if (!TextUtils.isEmpty(start_time.getText().toString().trim())) {
                    if (TextUtils.isEmpty(stop_time.getText().toString().trim())) {
                        mPresenter.office1(mCode, type.getTag().toString(), start_time.getText().toString().trim() + " 00:00:00",
                                start_time.getText().toString().trim() + " 23:59:59");
                    } else {
                        mPresenter.office1(mCode, type.getTag().toString(), start_time.getText().toString().trim() + " 00:00:00",
                                stop_time.getText().toString().trim() + " 23:59:59");
                    }
                }
            }
        } else {
            if ((int) type.getTag() == 0) {
                mPresenter.repairList(mCode, type.getTag().toString(), "", "");
            } else {
                if (!TextUtils.isEmpty(start_time.getText().toString().trim())) {
                    if (TextUtils.isEmpty(stop_time.getText().toString().trim())) {
                        mPresenter.repairList(mCode, type.getTag().toString(), start_time.getText().toString().trim() + " 00:00:00",
                                start_time.getText().toString().trim() + " 23:59:59");
                    } else {
                        mPresenter.repairList(mCode, type.getTag().toString(), start_time.getText().toString().trim() + " 00:00:00",
                                stop_time.getText().toString().trim() + " 23:59:59");
                    }
                }
            }

        }
    }


    private final static String TAG = MainActivity.class.getSimpleName();
    final Boolean SendMoudle = true;  //  这个表示是连接称重模块
    Boolean bisClosed = false;
    //    public ScaleView scaleView;
    Bundle bundle;
    private SQLiteDatabase mydb;
    static int dbversion = 1;
    private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
    private BluetoothAdapter mBluetoothAdapter = null;
    public Bluetooth_Scale btScale = null;
    public BluetoothLeClass bleScale = null;
    int BluetoothType;
    Boolean b_scaleIsConnect = Boolean.FALSE;
    Fragment_send_out.SCALENOW scalenow = new Fragment_send_out.SCALENOW();
    String BluetoothAddress;

    public void getBle() {
        try {
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // Checks if Bluetooth is supported on the device.
        if (mBluetoothAdapter == null) {
            ToastUtil.getInstance()._short(DetailedActivity.this, "不支持蓝牙");
            return;
        }

        mBluetoothAdapter.enable();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                final AlertDialog.Builder builder = new AlertDialog.Builder(DetailedActivity.this);
                builder.setTitle("此应用需要位置访问权限");
                builder.setMessage("请授予位置访问权限，以便此应用可以检测蓝牙。");
                builder.setPositiveButton(android.R.string.ok, null);
                builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
                        }
                    }
                });
                builder.show();
            }
        }
        if (btScale == null) btScale = Bluetooth_Scale.getBluetooth_scale();
        btScale.setOnReceivedDataListener(onReceivedDataListener);
        btScale.setOnConnectBlueListener(onConnectBlueListener);
        if (bleScale == null) {
            bleScale = BluetoothLeClass.getBluetoothLeClass();
            bleScale.initialize();
            bleScale.setOnConnectListener(onConnectListener);
            bleScale.setOnDataAvailableListener(new BluetoothLeClass.OnDataAvailableListener() {
                @Override
                public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {

                }

                @Override
                public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
                    byte[] buffer = characteristic.getValue();
                    OnReceivedData(buffer);
                }
            });
        }
        ReadConfig();
//        ChkAndConnectBl();
    }

    public BluetoothLeClass.OnConnectListener onConnectListener = new BluetoothLeClass.OnConnectListener() {
        @Override
        public void onConnect(BluetoothGatt gatt, int type) {
            if (type == 0) {
                MyApplication.b_scaleIsConnect = true;
            } else if (type == 1) {
                MyApplication.b_scaleIsConnect = false;
            }
            handler1.sendEmptyMessage(2);
        }
    };
    public Bluetooth_Scale.onReceivedDataListener onReceivedDataListener = new Bluetooth_Scale.onReceivedDataListener() {

        @Override
        public void onReceivedData(byte[] buf) {
            OnReceivedData(buf);
        }
    };
    public Bluetooth_Scale.onConnectBlueListener onConnectBlueListener = new Bluetooth_Scale.onConnectBlueListener() {
        @Override
        public void onConnect(int what, int arg) {
            if (arg < 2) {
                MyApplication.b_scaleIsConnect = Boolean.FALSE;
            } else {
                MyApplication.b_scaleIsConnect = Boolean.TRUE;
            }
            handler1.sendEmptyMessage(2);
        }
    };
    byte[] strdata = new byte[100];
    int pStrdata = 0;
    String oldWeight = "0";

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
//                        scaleView.setUnit(scalenow.sUnit);
            if (scalenow.bOverFlag) {
                sjzl.setText("");
            } else {
                if (!oldWeight.equals("0")) {
                    sjzl.setText(scalenow.sformatNetWeight + "g");
                }

                if (!scalenow.sformatNetWeight.equals("0")) {
                    lianjie.setEnabled(false);
                } else {
                    lianjie.setEnabled(true);
                }
                oldWeight = scalenow.sformatNetWeight;
            }

//                        scaleView.setZero(scalenow.bZeroFlag);
//                        scaleView.setStable(scalenow.bWeiStaFlag);
        }
    };

    void OnReceivedData(byte buf[]) {
        int bytes = buf.length;
        boolean result = false;
        for (int i = 0; i < bytes; i++) {
            if (buf[i] == 0x2) pStrdata = 0;
            else if ((buf[i] == 0x0a) || (buf[i] == 0x03)) {
                GetWeight(strdata, pStrdata);
                result = true;
                pStrdata = 0;
            } else {
                strdata[pStrdata] = buf[i];
                if (++pStrdata >= 100) pStrdata = 0;
            }
        }

        if (result)
            handler1.post(runnable);
    }

    void ChkAndConnectBl() {
        if (BluetoothAddress.length() > 0) {
            //ble或者双模模块
            if ((BluetoothType == BluetoothDevice.DEVICE_TYPE_LE)) {
                if ((bleScale != null) && bleScale.isConnect) {
                    bleScale.disconnect();
                }
                bleScale.connect(BluetoothAddress);
            } else {
                BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(BluetoothAddress);
                if (device != null) {
                    btScale.connect(device);
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 0:
                if (resultCode == RESULT_OK) {
                    Intent serverIntent = new Intent(DetailedActivity.this, DeviceListActivity.class);
                    startActivityForResult(serverIntent, 1);
                }
                break;
            case 1:
                if (resultCode == RESULT_OK) {
                    //String name=data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
                    BluetoothAddress = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                    BluetoothType = data.getExtras().getInt(DeviceListActivity.EXTRA_DEVICE_TYPE);
                    if (BluetoothAddress.length() > 0) {
                        //ble或者双模模块
                        if ((BluetoothType == BluetoothDevice.DEVICE_TYPE_LE)) {
                            if ((bleScale != null) && bleScale.isConnect) {
                                bleScale.disconnect();
                            }
                            bleScale.connect(BluetoothAddress);
                            WriteConfig();
                        } else {
                            BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(BluetoothAddress);
                            if (device != null) {
                                btScale.connect(device);
                                WriteConfig();
                            }
                        }
                    }
                }
                break;
        }
    }

    void GetWeight(byte[] databuf, int datalenght) {
        float f = 0;
        int dot = 1;
        scalenow.bOverFlag = false;
        scalenow.bWeiStaFlag = false;
        switch (databuf[0]) {
            case 'o':
            case 'O':
                scalenow.bOverFlag = true;
                break;
            case 'u':
            case 'U':
                scalenow.bWeiStaFlag = false;
                break;
            case 's':
            case 'S':
                scalenow.bWeiStaFlag = true;
                break;
        }
        if (datalenght > 7) {
            for (int i = 0; i < 7; i++) {
                if (databuf[i + 6 + 1] == '.') {
                    dot = -1;
                } else {
                    if (dot >= 0) {
                        f = f * 10 + ((databuf[i + 6 + 1] == ' ') ? 0 : (databuf[i + 6 + 1] - '0'));
                    } else {
                        f += Math.pow(10, dot) * (databuf[i + 6 + 1] - '0');
                        dot--;
                    }
                }
            }
            if (databuf[6] == '-') f *= -1;
        }
        if (dot < 0) dot = (-dot) - 1;
        else dot = 0;
        scalenow.fformatNetWeight = f;
        scalenow.sformatNetWeight = String.format("%1." + String.valueOf(dot) + "f", f);
        if (datalenght > 14) {
            scalenow.sUnit = new String(databuf, 14, datalenght - 14);
        }
        scalenow.bZeroFlag = (f == 0);
    }

    public void ReadConfig() {
        SharedPreferences settings = getSharedPreferences(PubFunction.PREFS_NAME, Context.MODE_PRIVATE);
        BluetoothAddress = settings.getString("BluetoothAddress", "");
        BluetoothType = settings.getInt("BluetoothType", 0);
    }

    public void WriteConfig() {

        SharedPreferences settings = getSharedPreferences(PubFunction.PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putInt("BluetoothType", BluetoothType);
        editor.putString("BluetoothAddress", BluetoothAddress);
        editor.commit();
    }

    public static class SCALENOW {
        public String sformatNetWeight = "0";
        public String sUnit = " g ";
        public float fformatNetWeight;
        public boolean bZeroFlag;
        public boolean bWeiStaFlag;
        public boolean bOverFlag;
    }
}
